﻿Ext.define('SmartClient.controller.ProductsAmountPopupController',
   {
      extend: 'Deft.mvc.ViewController',

      init: function ()
      {
         this.getOkButton().setHandler(this.confirmAmount, this);
         this.getAmountTextfield().addListener('keyup', this.confirmAmountOnPressEnter, this);
         return this.callParent(arguments);
      },

      // Element IDs here
      // DeftJS will create a getter and setter for property
      control:
         {
            amountTextfield: true,
            unitsLabel: true,
            okButton: true
         },

      confirmAmount: function()
      {
         var amountToOrder = parseFloat(this.getAmountTextfield().getValue()),
             thisVeiw = this.getView(),
             availableAmount = thisVeiw.getAvailableAmount();

         if (availableAmount >= amountToOrder)
         {
            var productsController = Ext.getCmp('productsPanel').getController(),
                addedProducts = SmartClient.utils.CookieUtils.getCookieValue(SmartClient.Application.ADDED_PRODUCTS_COOKIE),
                productID = thisVeiw.getProductId(),
                addedProductsAmount = productsController.getAddedProductsAmount(productID);

            SmartClient.utils.CookieUtils.eraseCookie(SmartClient.Application.ADDED_PRODUCTS_COOKIE);
            if (addedProductsAmount == 0)
            {
               SmartClient.utils.CookieUtils.setCookie(SmartClient.Application.ADDED_PRODUCTS_COOKIE, (addedProducts ? addedProducts + SmartClient.Application.ADDED_PRODUCTS_DELIMITER : '')
                  + productsController.self.generateAddedProductFromTemplate(productID, amountToOrder), 30);
            }
            else
            {
               var orderedItem = productsController.self.generateAddedProductFromTemplate(productID, addedProductsAmount),
                   newItem = productsController.self.generateAddedProductFromTemplate(productID, amountToOrder);
               SmartClient.utils.CookieUtils.setCookie(SmartClient.Application.ADDED_PRODUCTS_COOKIE, addedProducts.replace(orderedItem, newItem), 30);
            }
            productsController.refreshViewAddedProductsButtonText();
            thisVeiw.close();
         }
         else
         {
            // Some message if avalable amount is lower then amount of product to order
         }
      },

      confirmAmountOnPressEnter: function (form, event)
      {
         if ((event.getKey() == 13) && !this.getOkButton().isDisabled())
         {
            this.confirmAmount();
         }
      }
   });